package main

import (
	"fmt"
	"mygoedu/day11/class/socket"
	"net"
	"strconv"
	"time"
)

//收发简单的字符串消息
func main_tcp_server1() {
	ip := "127.0.0.1" //ip换成0.0.0.0和空字符串试试
	port := 5656      //改成1023试一下，会报bind: permission denied
	tcpAddr, err := net.ResolveTCPAddr("tcp4", ip+":"+strconv.Itoa(port))
	socket.CheckError(err)
	listener, err := net.ListenTCP("tcp4", tcpAddr)
	socket.CheckError(err)
	fmt.Println("waiting for client connection ......")
	conn, err := listener.Accept()
	socket.CheckError(err)
	fmt.Printf("establish connection to client %s\n", conn.RemoteAddr().String()) //操作系统会随机给客户端分配一个49152~65535上的端口号
	request := make([]byte, 256)                                                  //设定一个最大长度，防止flood attack
	_, err = conn.Read(request)
	socket.CheckError(err)
	fmt.Printf("receive request %s\n", string(request))
	n, err := conn.Write([]byte("hello " + string(request)))
	socket.CheckError(err)
	fmt.Printf("write response %d bytes\n", n)
	time.Sleep(1 * time.Second)
	_, err = conn.Write([]byte("oops"))
	socket.CheckError(err) //client端已关闭连接，再往conn里写会发生错误
}

//go run socket/server/tcp_server1.go
